<?php

// 支付授权目录 112.124.44.172/wshop/
// 支付请求示例 index.php
// 支付回调URL http://112.124.44.172/wshop/?/Order/payment_callback
// 维权通知URL http://112.124.44.172/wshop/?/Service/safeguarding
// 告警通知URL http://112.124.44.172/wshop/?/Service/warning

/*
 * Copyright (C) 2014 Administrator.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

/**
 * 订单类
 */
class Order extends Controller {

    public function __construct($ControllerName, $Action, $QueryString) {
        parent::__construct($ControllerName, $Action, $QueryString);
        $this->loadModel('Db');
    }

    // 支付发起页面
    public function payment() {
        
    }

    // 支付回调页面
    public function payment_callback() {
        
    }

    // 支付回调页面
    public function payment_notify() {
        // postStr
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $this->loadModel('WechatSdk');
        $Stoken = WechatSdk::getServiceAccessToken();
        // orderid 
        $orderId = intval($_GET['out_trade_no']);
        // 微信交易单号
        $transaction_id = $_GET['transaction_id'];
        // 银行交易单号
        $bank_billno = $_GET['bank_billno'];
        // update
        $UpdateSQL = sprintf("UPDATE `orders` SET `wepay_serial` = '%s',`status` = 'payed',`bank_billno` = '%s' WHERE `order_id` = %s", $transaction_id, $bank_billno, $orderId);
        $this->Db->query($UpdateSQL);
        $UpdateSQL2 = sprintf("UPDATE `orders_detail` SET `is_returned` = 0 WHERE `order_id` = $orderId;");
        $this->Db->query($UpdateSQL2);
        // 刷新clien_id
        $this->Db->query('UPDATE `orders` SET `client_id` = (SELECT client_id FROM `clients` WHERE `client_wechat_openid` = `orders`.wepay_openid) WHERE `orders`.client_id IS NULL;');
        // 发送消息提示
        # Messager::sendText($Stoken, $postObj->OpenId, "交易成功，请等待发货。" . time());
        // 必须返回success，不然会不断通知
        echo 'success';
    }

    // 订单确认页面
    public function cart() {
        $this->loadModel('User');

        if (Controller::inWechat()) {
            $OauthURL = "http://112.124.44.172/wshop/wxpay.php";
            $FinalURL = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            include_once(dirname(__FILE__) . "/../lib/Tools.php");
            $this->loadModel('WechatSdk');
            $AccessCode = WechatSdk::getAccessCode($OauthURL, "snsapi_base");
            if ($AccessCode !== FALSE) {
                // 获取到accesstoken和openid
                $AResult = WechatSdk::getAccessToken($AccessCode);
                #$openId = $AResult->openid;
                $AccessToken = $AResult->access_token;
            }
            // shareaddress
            // 随机字符串
            $nonceStr = rand(100000, 999999);
            // Unix时间戳
            $timestamp = time();
            $myaddr = new SignTool();
            $myaddr->setParameter("appid", APPID);
            $myaddr->setParameter("url", $FinalURL);
            $myaddr->setParameter("noncestr", $nonceStr);
            $myaddr->setParameter("timestamp", $timestamp);
            $myaddr->setParameter("accesstoken", $AccessToken);
            $addrsign = $myaddr->genSha1Sign();
            unset($AccessCode);
            // shareaddress
        }

        $this->Smarty->assign('userInfo', (array) $this->User->getUserInfo());
        $this->Smarty->assign('appid', APPID);
        $this->Smarty->assign('timestamp', $timestamp);
        $this->Smarty->assign('nonceStr', $nonceStr);
        $this->Smarty->assign('addrsign', $addrsign);
        $this->show();
    }

    /**
     * Ajax生成订单
     */
    public function ajaxCreateOrder() {
        $this->loadModel('mOrder');
        $this->loadModel('User');

        echo $this->mOrder->create($_POST['openid'], '', json_decode(str_replace('p', '', $_POST['cartData']), true), $_POST['addrData'], $_POST['balancePay'] == 1);
    }

    /**
     * Ajax获取订单请求数据包
     */
    public function ajaxGetBizPackage() {
        include_once(dirname(__FILE__) . "/../lib/Tools.php");
        include_once(dirname(__FILE__) . "/../lib/wepaySdk/WxPayHelper.php");
        $orderId = intval($_POST['orderId']);
        $wxPayHelper = new WxPayHelper();
        $wxPayHelper->setParameter("bank_type", "WX");
        // 商品名称 如果只有一件直接显示，如果多件，显示母婴用品吧。
        $wxPayHelper->setParameter("body", "熹贝母婴用品");
        // partner id
        $wxPayHelper->setParameter("partner", PARTNER);
        // 唯一订单id
        $wxPayHelper->setParameter("out_trade_no", $orderId);
        // 订单总计
        #echo $this->countOrderSum();
        $wxPayHelper->setParameter("total_fee", $this->countOrderSum($orderId) * 100);
        $wxPayHelper->setParameter("fee_type", "1");
        $wxPayHelper->setParameter("notify_url", "http://112.124.44.172/wshop/?/Order/payment_notify/");
        $wxPayHelper->setParameter("spbill_create_ip", $this->getIp());
        $wxPayHelper->setParameter("input_charset", "UTF-8");
        $biz_package = $wxPayHelper->create_biz_package();
        echo $biz_package;
    }

    /**
     * cookie
     * 计算订单总量
     * @return <float>
     */
    private function countOrderSum($orderid) {
        $sum = $this->Db->query("SELECT `order_amount` FROM `orders` WHERE `order_id` = $orderid;");
        return $sum[0]['order_amount'];
    }

    /**
     * expressDetail 查看物流情况
     */
    public function expressDetail($Query) {
        if (!isset($Query->order_id) && $Query->order_id > 0) {
            exit(0);
        }
        $Query->order_id = addslashes($Query->order_id);
        // 商品列表
        $orderProductsList = $this->Db->query("SELECT `catimg`,`pi`.product_name,`pi`.product_id,`sd`.product_count,`sd`.product_discount_price FROM `orders_detail` sd LEFT JOIN `vProductInfo` pi on pi.product_id = sd.product_id WHERE `sd`.order_id = " . $Query->order_id);
        // 订单信息
        $orderData = $this->Db->query("SELECT * FROM `orders` WHERE `order_id` = " . $Query->order_id . ';');
        $orderData = $orderData[0];
        $expressCode = include dirname(__FILE__) . '/../config/express_code.php';
        $orderData['express_com1'] = $expressCode[$orderData['express_com']];
        $this->Smarty->assign('orderdetail', $orderData);
        $this->Smarty->assign('productlist', $orderProductsList);
        $this->show();
    }

    /**
     * 订单取消
     * @todo a lot
     */
    public function cancelOrder() {
        $orderId = $_POST['orderId'];
        $cancelSql = "UPDATE " . TABLE_ORDERS . " SET `status` = 'canceled' WHERE `order_id` = $orderId;";
        $rst = $this->Db->query($cancelSql);
        # echo $cancelSql;
        echo $rst > 0 ? "1" : "0";
    }

    /**
     * 确认收货
     */
    public function confirmExpress($Query) {
        // orders >> received
        $orderId = intval($_POST['orderId']);
        $updateSql = "UPDATE `" . TABLE_ORDERS . "` SET status = 'received' WHERE `order_id` = $orderId;";
        echo $this->Db->query($updateSql);
    }

    /**
     * 订单发货
     */
    public function ExpressReady() {
        $this->loadModel('mOrder');
        $this->loadModel('WechatSdk');

        $orderId = intval($_POST['orderId']);
        $expressCode = $_POST['ExpressCode'];
        $expressCompany = $_POST['expressCompany'];

        if ($this->mOrder->despacthGood($orderId, $expressCode, $expressCompany)) {
            $expressList = include dirname(__FILE__) . '/../config/express_code.php';
            $orderData = $this->Db->query("SELECT `tel_number`,`wepay_openid` FROM `orders_address`,`orders` WHERE `orders`.`order_id` = $orderId;");
            $stoken = WechatSdk::getServiceAccessToken();
            // sms notify
            $this->loadModel('weiMiSms');
            // 【熹贝母婴】尊敬的客户，您的订单已发货，快递单号为：151215411002，请您耐心等待。
            $this->weiMiSms->sendSmsTemplate($orderData[0]['tel_number'], WEIMITEMPLATE1, array($expressList[$expressCompany], $expressCode));
            $rst = Messager::sendText($stoken, $orderData[0]['wepay_openid'], "尊敬的客户，您的订单已发货，快递单号为：$expressCode，请您耐心等待。<a href='http://112.124.44.172/wshop/?/Order/expressDetail/order_id=$orderId'>点击查看快递详情</a>");
            if ($rst['errcode'] != 0) {
                $this->reportError('发货通知 微信消息发送失败。错误代码' . $rst['errcode'], __FILE__);
            }
            echo 1;
        } else {
            echo 0;
        }
    }

    /*
     * @HttpPost only
     * 获取快递跟踪情况
     * @return <html>
     */

    public function ajaxGetExpressDetails() {
        $typeCom = $_POST["com"]; //快递公司
        $typeNu = $_POST["nu"];  //快递单号
        # $AppKey = '73783e4f51c1201f';
        # $url = "http://wap.kuaidi100.com/wap_result.jsp?rand=" . time() . "&id=$typeCom&fromWeb=null&&postid=$typeNu";
        $url = "http://api.ickd.cn/?id=105049&secret=c246f9fa42e4b2c1783ef50699aa2c4d&com=$typeCom&nu=$typeNu&type=html&encode=utf8";

        # $express_com = include dirname(__FILE__) . '/../../config/com_code.php';
        //优先使用curl模式发送数据
        $res = Curl::get($url);
        echo $res;
    }

    public function test() {
        
    }

}
